package com.zbf.cnofig;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/6/22  15:34
 * 描述:
 */
@Configuration
public class RequestRateLimitConfig {

    @Bean
    public KeyResolver getUriKeyResolver(){
        //根据uri（path）进行解析
       return new KeyResolver() {
           public Mono<String> resolve(ServerWebExchange exchange) {
               return Mono.just(exchange.getRequest().getPath().toString());
           }
       };

    }


    @Bean("keyResolver")
    @Primary
    public KeyResolver getIPKeyResolver(){
        //根据IP进行解析
        return new KeyResolver() {
            public Mono<String> resolve(ServerWebExchange exchange) {
                System.out.println(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
                return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
            }
        };
    }


    @Bean
    public KeyResolver getUserIdKeyResolver(){
        //根据IP进行解析
        return new KeyResolver() {
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
            }
        };
    }
}
